package com.example.administrator.about_huanxin.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.about_huanxin.R;
import com.example.administrator.about_huanxin.ShareprefenceUtils;
import com.example.administrator.about_huanxin.model.UserEntity;
import com.example.administrator.about_huanxin.presenter.activity.RegisiterPresenter;
import com.example.administrator.about_huanxin.presenter.activity.RegisiterPresenterImp;
import com.example.administrator.about_huanxin.view.activity.RegisterActivityView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import butterknife.ButterKnife;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

public class RegisiterActivity extends BaseActivity implements RegisterActivityView {

    private EditText ed1;
    private EditText ed2;
    private EditText ed3;
    private Button btnOk;
    private ImageView img;
    private TextView jump_tv;

    private int index;
    private RegisiterPresenter regisiterPresenter;
    private UserEntity userEntity;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    showToast("上传头像成功!");
                    break;

                case 1:
                    showToast("上传头像失败!");
                    break;

                case 2:
                    showToast("保存用户信息失败!");
                    break;

                case 3:
                    showToast("注册环信失败!");
                    break;

                case 4:
                    showToast("注册环信成功");
                    break;
            }
        }
    };

    private void showToast(String str) {
        Toast.makeText(RegisiterActivity.this, str, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void setTitleText(TextView tv) {
        tv.setText("注册");
    }

    @Override
    public void setVisibleBtn(Button btn) {
        btn.setVisibility(View.GONE);
    }

    @Override
    public View addContent(LayoutInflater inflater, FrameLayout content) {
        View view = inflater.inflate(R.layout.activity_profile,content,true);
        return view;
    }

    @Override
    public void initContent(View view) {
        initView(view);
        img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, 100);
            }
        });

        jump_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(RegisiterActivity.this,LoginActivity.class));
                finish();
            }
        });

        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(ed1.getText())) {
                    Toast.makeText(RegisiterActivity.this, "姓名不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                userEntity.setNickname(ed1.getText().toString());
                if (TextUtils.isEmpty(ed2.getText())) {
                    Toast.makeText(RegisiterActivity.this, "用户名不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                userEntity.setUsername(ed2.getText().toString());
                if (TextUtils.isEmpty(ed3.getText())) {
                    Toast.makeText(RegisiterActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                userEntity.setPassword(ed3.getText().toString());
                regisiterPresenter.uploadUserIcon(userEntity);
            }
        });
    }

    private void initView(View view) {
        ed1 = (EditText) view.findViewById(R.id.ed1);
        ed2 = (EditText) view.findViewById(R.id.ed2);
        ed3 = (EditText) view.findViewById(R.id.ed3);
        btnOk = (Button) view.findViewById(R.id.btn_ok);
        img = (ImageView) view.findViewById(R.id.img);
        jump_tv = (TextView) view.findViewById(R.id.jump_tv);

        regisiterPresenter = new RegisiterPresenterImp(this);
        userEntity = new UserEntity();
    }

    private void crop(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");

        intent.setDataAndType(uri, "image/*");

        intent.putExtra("crop", "true");

        intent.putExtra("aspectX", 1);

        intent.putExtra("aspectY", 1);

        intent.putExtra("outputX", 250);

        intent.putExtra("outputY", 250);

        intent.putExtra("scale", true);


        intent.putExtra("return-data", false);

        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

        intent.putExtra("noFaceDetection", true); // no face detection

        startActivityForResult(intent, 200);

    }

    private Bitmap decodeUriAsBitmap(Uri uri) {

        Bitmap bitmap = null;

        try {

            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));

        } catch (FileNotFoundException e) {

            e.printStackTrace();

            return null;

        }

        return bitmap;

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (data != null) {
                Uri uri = data.getData();
                crop(uri);
            }
        } else if (requestCode == 200) {
            Bitmap bitmap = decodeUriAsBitmap(data.getData());
            if (bitmap != null) {
                img.setImageBitmap(bitmap);
                //保存图片(/data/packagename/files)
                try {
                    FileOutputStream stream = openFileOutput(ed2.getText().toString() + ".jpg", Context.MODE_PRIVATE);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

                    String path = ed2.getText().toString() + ".jpg";
                    File file = new File(getFilesDir(), path);
                    BmobFile bmobFile = new BmobFile(file);
                    userEntity.setIcon(bmobFile);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void afterUploadIcon(boolean success) {
        if (success) {
            //成功则更新加载界面信息:头像上传成功
            handler.sendEmptyMessage(0);
        } else {
            //吐司提示:注册失败
            handler.sendEmptyMessage(1);
        }
    }

    @Override
    public void afterSaveUserInfo(boolean success) {
        if (success) {
            //成功跳转页面
        } else {
            //失败吐司
            handler.sendEmptyMessage(2);
        }
    }

    @Override
    public void afterLoginEMClient(boolean success) {
        if(success){
            handler.sendEmptyMessage(4);
            startActivity(new Intent(this,LoginActivity.class));
            finish();
        }else {
            handler.sendEmptyMessage(3);
        }
    }

//    @Override
//    public void afterFinalLoginEmClient(boolean success) {
//        if(success){
//
//            handler.sendEmptyMessage(5);
//        }else {
//            handler.sendEmptyMessage(4);
//        }
//        ShareprefenceUtils.setResult(RegisiterActivity.this, "user", ed2.getText().toString());
//        ShareprefenceUtils.setResult(RegisiterActivity.this, "pwd", ed3.getText().toString());
//        startActivity(new Intent(RegisiterActivity.this, MainActivity.class));
//        finish();
//    }
}
